﻿/*
 * Copyright © 2011 Tristan Reeves, treeves@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Linq;

namespace Sprinkles
{
    public class FutureDeployedObject<T> : IFutureDeployedObject
    {
        private readonly Func<string> m_NameCallback;
        private readonly Func<string, object> m_ContainerObjectRetrievingCallback;
        internal FutureDeployedObject(Func<string> nameCallback, Func<string, object> containerCallback)
        {
            m_NameCallback = nameCallback;
            m_ContainerObjectRetrievingCallback = containerCallback;
        }

        public bool IsFactoryObject
        {
            get
            {
                const string IFactoryObjectName ="Spring.Objects.Factory.IFactoryObject";
                var result = typeof(T)
                    .GetInterfaces()
                    .Any
                    (
                        ifc => ifc.GetType().FullName.Equals(IFactoryObjectName)
                    );
                return result;
            }
        }
        public T Retrieve()
        {
            var nam = m_NameCallback();
            if (IsFactoryObject) nam = "&" + nam;

            return (T)m_ContainerObjectRetrievingCallback(nam);
        }
        public FutureDeployedObject<TProduct> ToFactoryProduct<TProduct>()
        {
            var result = new FutureDeployedObject<TProduct>(m_NameCallback, m_ContainerObjectRetrievingCallback);
            return result;
        }
        public FutureDeployedObject<TFactory> ToFactory<TFactory>()
        {
            var result = new FutureDeployedObject<TFactory>(m_NameCallback, m_ContainerObjectRetrievingCallback);
            return result;
        }
        public string GetName()
        {
            return m_NameCallback();
        }
    }
}
